<?php
require_once(APPPATH.'controllers/admin.php');
class Song extends Admin {
	
	public function __construct() {
		$this->view['controller_name'] = 'song'; // Send params to the view to config
		parent::__construct();
		
		$this->load->model('Karas_model');
		$this->load->library('session');
	}
	
	public function index() {
		$this->view['template'] = 'admin/song/list';
		$keyword 	= $this->input->post('search_id');
		
		$where 		= "karas.name LIKE '%{$keyword}%'";
		
		// Get all the song
		$this->view['data'] = array(
			'keyword'		=> $keyword, 	
			'title' 		=> 'Songs',
			'lists'			=> $this->Karas_model->get_limit($this->per_page, $this->page, $where)->result_array(),
				
			'pagination'	=> $this->_pagination(
						'admins/song/index/page', 
						$this->Karas_model->count_all($where), 
						$this->per_page
					),
			'table_titles'	=> array(
					'id' 				=> 'ID', 
					'name'  			=> 'Name'
			)		
		);
		
		$this->_render($this->view); 
	}
	
	public function delete () {
		$id = $this->input->get('id');
		$this->Karas_model->delete($id);
	}
	
	public function edit($id = null) {
		$success_msg = '';
		$this->view['template'] = 'admin/song/edit';
		
		$this->load->library('form_validation');
		
		$this->form_validation->set_rules('code', 'Code', 'required');
		$this->form_validation->set_rules('name', 'Name', 'required');
		
		if ($id) {
			$data = $this->Karas_model->get($id)->result_array();
			$data = $data[0];
		}
		
		if ($this->input->post('save')) {
			
			var_dump($this->form_validation->run('form'));
			$data = $this->_get_post();
			if ($this->form_validation->run('form')) {
				if ($id) {
					$this->Karas_model->update($data, $id);
				} else {
					$this->Karas_model->insert($data);
					$data = $this->_reset();
				}	
			}
			
		}
		
		$this->view['data'] = array (
				'title' 		=> 'Edit song',
				'success_msg'	=> $success_msg,
				'form'			=> isset($data) ? $data : $this->_get_post()
		);
		
		$this->_render($this->view);
	}
	
	private function _get_post() {
		return array (
				'name'			=> $this->input->post('name'),
				'code'			=> $this->input->post('code'),
				'short_cont'	=> $this->input->post('short_cont'),
				'author'		=> $this->input->post('author'),
			);
	}
	
	private function _reset() {
		return array (
				'name'			=> '',
				'code'			=> '',
				'short_cont'	=> '',
				'author'		=> '',
		);
	}
}